<template>
  <div class="app-container search-table-box aidex-table">
    <el-card shadow="never" ref="queryRef" style="margin-bottom: 12px;" class="search_card" v-show="showSearch">
      <div class="filter-container">
        <div class="search_box" style="padding-bottom: 16px">
          <el-form :model="queryParams" ref="queryForm" label-width="80px" size="mini">
            <el-row :gutter="16">
              <el-col :md="6" >
                <el-form-item prop="searchValues">
                  <el-select
                    v-model="queryParams.searchValues"
                    multiple
                    filterable
                    remote
                    reserve-keyword
                    clearable
                    placeholder="请输入销方名称/发票号码/发票代码"
                    :remote-method="remoteSearchValue"
                    @change="handleQuery"
                    :loading="remoteSearchValueLoading"
                    style="width: 315px;margin-left: -78px"
                  >
                    <el-option
                      v-for="item in searchValueOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :md="2" >
                <el-button size="mini"  @click="toggleAdvanced" type="primary" plain style="padding: 6px 15px;">
                  {{ advanced ? '收起' : '展开' }}
                  <i :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
                </el-button>
              </el-col>
              <el-col :md="16" align="right" class="longBtnBar">
                <el-form-item >
                  <el-button class="filter-item" type="primary" @click="handleImport">导入匹配</el-button>
                  <el-button class="filter-item" style="margin-left: 8px" @click="resetQuery">标记完成</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <div class="search_advanced_bar" v-if="advanced">
              <el-card shadow="never" >
                <el-row :gutter="16" >
<!--                  <el-col :md="6" >-->
<!--                    <el-form-item label="公司" prop="siteCode">-->
<!--                      <el-input v-model="queryParams.params.companynames" maxlength = 0 clearable placeholder="请选择公司" >-->
<!--                        <el-button slot="append" icon="el-icon-search" @click="openSearchsiteCodeDialogOpen">-->
<!--                        </el-button>-->
<!--                      </el-input>-->
<!--                    </el-form-item>-->
<!--                  </el-col>-->
                  <el-col :md="8" >
                    <el-form-item label="开票日期">
                      <el-date-picker
                        v-model="daterangeInvoiceDate"
                        style="width: 100%"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                      ></el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :md="6" align="right" style="float: right;" >
                    <el-form-item>
                      <el-button class="filter-item" type="primary" @click="handleQuery">搜索</el-button>
                      <el-button class="filter-item" style="margin-left: 8px" @click="resetQuery">重置</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="16">
                  <el-col :md="12" >
                    <el-form-item label="发票类型" prop="invoiceType">
                      <el-row :gutter="16">
                        <el-col :md="4" >
                          <el-checkbox v-model="checkAllInvoiceType" :indeterminate="isInvoiceTypeIndeterminate" label="全选" size="mini" @change="checkAll($event,'invoiceType')" border></el-checkbox>
                        </el-col>
                        <el-col :md="19" >
                          <el-checkbox-group v-model="queryParams.invoiceTypes" @change="handleCheckedChange($event,'invoiceType')">
                            <el-checkbox v-for="dict in dict.type.invoice_type" :label="dict.value" :key="dict.value">{{dict.label}}</el-checkbox>
                          </el-checkbox-group>
                        </el-col>
                      </el-row>
                    </el-form-item>
                  </el-col>
                  <el-col :md="12" >
                    <el-form-item label="匹配状态" prop="signStatus">
                      <el-row :gutter="16">
                        <el-col :md="4" >
                          <el-checkbox v-model="checkAllSignStatus" :indeterminate="isSignStatusIndeterminate" label="全选" size="mini" @change="checkAll($event,'signStatus')" border></el-checkbox>
                        </el-col>
                        <el-col :md="18" >
                          <el-checkbox-group v-model="queryParams.signStatuses" @change="handleCheckedChange($event,'signStatus')">
                            <el-checkbox v-for="dict in dict.type.bus_yes_no" :label="dict.value" :key="dict.value">{{dict.label}}</el-checkbox>
                          </el-checkbox-group>
                        </el-col>
                      </el-row>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="16">
                  <el-col :md="12" >
                    <el-form-item label="是否供应商" prop="processStatus">
                      <el-input v-model="queryParams.erpSerialNumber" placeholder="请输" />
                    </el-form-item>
                  </el-col>
                  <el-col :md="12" >
                    <el-form-item label="ERP流水号" prop="erpSerialNumber">
                      <el-input v-model="queryParams.erpSerialNumber" placeholder="请输入" />
                    </el-form-item>
                  </el-col>

                </el-row>
              </el-card>
            </div>
          </el-form>
        </div>
      </div>
    </el-card>
    <el-card shadow="never" >
      <template #header>
        <el-row>
          <el-col :span="8">
            <div class="card-header">
              <el-button disabled type="text">三单匹配信息</el-button>
            </div>
          </el-col>
          <el-col :span="16">
            <div class="btn_box" align="right" style="float: right;">
              <el-button
                class="filter-item"
                style="margin-left: 8px;"
                icon="el-icon-download"
                @click="handleExport"
                size="mini"
                v-hasPermi="['doc:checkininvoice:export']"
              >导出</el-button>
              <right-toolbar :showSearch.sync="showSearch" :columns.sync="columns" :columnsKey.sync="columnsKey" @showSearchFun="showSearchFun" @queryTable="getList" :tableKey.sync="tableKey"></right-toolbar>
            </div>
          </el-col>
        </el-row>
      </template>

      <el-table
        border
        stripe
        default-expand-all
        ref="tableRef"
        :key="tableKey"
        v-loading="loading"
        :data="checkininvoiceList"
        @selection-change="handleSelectionChange"
        :row-style="rowClass"
        :header-cell-style= "{
                'font-size': '14px !important',
                'font-weight': '500 !important',
                'color': 'rgb(0 0 0)',
                'background-color': 'rgb(205 224 255)',
              }"
        highlight-current-row style="width: 100%;"
        :height="tableHeight"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" align="center" width="55">
          <template slot-scope="scope">
            <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
          </template>
        </el-table-column>

        <template v-for="item in columns">
<!--          <el-table-column label="公司" align="center" key="siteName" prop="siteName" v-if="item.visible && item.label=='公司'" :show-overflow-tooltip="true"/>-->
          <el-table-column label="发票类型" align="center" key="invoiceTypeName" prop="invoiceTypeName" v-if="item.visible && item.label=='发票类型'"  width="100"/>
          <el-table-column label="发票号码" align="center" key="invoiceNo" prop="invoiceNo"  v-if="item.visible && item.label=='发票号码'"  width="110"/>
          <el-table-column label="发票代码" align="center" key="invoiceCode" prop="invoiceCode" v-if="item.visible && item.label=='发票代码'"  width="120" />
          <el-table-column label="匹配状态" align="center" key="signStatusName" prop="signStatusName"  v-if="item.visible && item.label=='匹配状态'"  width="100">
            <template slot-scope="scope">
              <span>✘</span>
            </template>✘✘✘✘✘✘✘
          </el-table-column>✖️✖️
          <el-table-column label="发票状态" align="center" key="invoiceStatusName" prop="invoiceStatusName"  v-if="item.visible && item.label=='发票状态'"  width="100"/>
          <el-table-column label="开票日期" align="center" key="invoiceDate" prop="invoiceDate" v-if="item.visible && item.label=='开票日期'"  width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.invoiceDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="销方名称"     align="center" key="sellerName" prop="sellerName"  v-if="item.visible && item.label=='销方名称'"  width="180" :show-overflow-tooltip="true"/>
          <el-table-column label="金额(不含税)" align="center" key="feeWithoutTax" prop="feeWithoutTax"  v-if="item.visible && item.label=='金额(不含税)'"  width="150"/>
          <el-table-column label="税额"         align="center" key="tax" prop="tax"  v-if="item.visible && item.label=='税额'"  width="100"/>
          <el-table-column label="金额(含税)"   align="center" key="fee" prop="fee"  v-if="item.visible && item.label=='金额(含税)'"  width="100"/>
          <el-table-column label="发票备注" align="center" key="invoiceRemark" prop="invoiceRemark"  v-if="item.visible && item.label=='发票备注'"  width="100" :show-overflow-tooltip="true"/>
          <el-table-column label="ERP发票流水号" align="center" key="erpSerialNumber" prop="erpSerialNumber"  v-if="item.visible && item.label=='ERP发票流水号'"  width="180" :show-overflow-tooltip="true"/>
        </template>
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="220">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleOpenInvoice(scope.row)"
              v-hasPermi="['doc:invoice:edit']"
            >详情</el-button>
            <el-divider direction="vertical"></el-divider>

            <el-popover
              placement="top"
              width="160"
              trigger="click">
              <p>请确认该操作？</p>
              <div style="text-align: right; margin: 0">
                <el-button type="warning" size="mini" >取消</el-button>
                <el-button type="primary" size="mini" >确定</el-button>
              </div>
              <el-button  type="text" slot="reference">取消匹配</el-button>
            </el-popover>


          </template>
        </el-table-column>
        <div slot="empty">
          <svg-icon icon-class="search-none" style="font-size: 64px;" />
          <p>暂无数据</p>
        </div>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 导入对话框 -->
      <el-dialog v-dialogDrag  :close-on-click-modal="false" :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <div class="dialog_box">
          <el-upload
            ref="upload"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              请先导出模板，编辑完后导入！
              <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                       @click="importTemplate">下载模板</el-link>
            </div>
            <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>

          </el-upload>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" type="primary" @click="submitFileForm" :loading="upload.isUploading">确 定</el-button>
          <el-button size="mini" @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 查看发票 -->
      <el-dialog v-dialogDrag  :close-on-click-modal="false" title="详请" :visible.sync="invoiceOpen" width="1400px" append-to-body>
        <div class="dialog_box" style="height:580px;">
          <el-row>
            <el-col :span="10">
              <div style="height:575px; overflow-y: auto">
                <el-tabs type="border-card">
                  <el-tab-pane label="发票信息">
                    <el-descriptions class="margin-top" title="基本信息" :column="2" size="small" border>
                      <template slot="title">
                        <div>基本信息 <span class="invoice-type">{{detailForm.invoiceTypeName}}</span></div>
                      </template>
                      <el-descriptions-item>
                        <template slot="label">
                          发票代码:
                        </template>
                        011002100113
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template slot="label">
                          发票号码:
                        </template>
                        04676496
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template slot="label">
                          开票日期:
                        </template>
                        2023-12-12
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template slot="label">
                          金额(不含税):
                        </template>
                        ¥394.34
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template slot="label">
                          税额:
                        </template>
                        ¥23.66
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template slot="label">
                          金额(含税):
                        </template>
                        ¥418
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template slot="label">
                          校验码:
                        </template>
                        00825700862314111697
                      </el-descriptions-item>
                    </el-descriptions>
                    <el-descriptions class="margin-top" title="抬头信息" :column="1" size="small" border>
                      <template slot="extra">
                        <el-radio-group v-model="isWithout" size="mini">
                          <el-radio-button label="销方"></el-radio-button>
                          <el-radio-button label="购方"></el-radio-button>
                        </el-radio-group>
                      </template>
                      <el-descriptions-item>
                        <template slot="label">
                          名称:
                        </template>
                        北京中健云康供应链科技有限公司
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template slot="label">
                          纳税识别号:
                        </template>
                        91110400MA020G766F
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template slot="label">
                          地址、电话:
                        </template>
                        北京市大兴区礼贤镇元平北路1号自贸试验区大兴机场片区自贸创新服务中心E10栋三层0282号 13521228583北京市大兴区礼贤镇元平北路1号自贸试验区大兴机场片区自贸创新服务中心E10栋三层0282号 13521228583
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template slot="label">
                          开户行及账号:
                        </template>
                        中国建设银行股份有限公司广州粤电支行 44050138220100001803
                      </el-descriptions-item>
                    </el-descriptions>
                    <el-descriptions class="margin-top" title="商品明细" :column="1" size="small" border >
                      <template slot="extra">
                        <el-radio-group v-model="isWithout" size="mini">
                          <el-radio-button label="含税"></el-radio-button>
                          <el-radio-button label="不含税"></el-radio-button>
                        </el-radio-group>
                      </template>
                      <el-descriptions-item>
                        <el-table
                          border
                          stripe
                          default-expand-all
                          ref="invoiceDetailEntry"
                          v-loading="loading"
                          :data="invoiceEntryList"
                          :header-cell-style= "{
                          'font-size': '12px !important',
                          'font-weight': '500 !important',
                          'color':'#FFF',
                          'padding': '0px 0',
                          'background-color':'rgb(51 112 255 / 80%)',
                          textAlign: 'left',
                          'height': '30px !important'
                        }"
                          :cell-style="{ padding: '8px 10px 8px 0', textAlign: 'left' }"
                          highlight-current-row
                          style="width: 555px;margin-left: -32px;margin-top: -10px;"
                          height="300px"
                        >
                          <el-table-column label="序号" align="center" prop="index" width="50">
                            <template slot-scope="scope">{{scope.$index+1}}</template>
                          </el-table-column>
                          <el-table-column label="项目名称" align="left" prop="itemName" width="120" show-overflow-tooltip/>
                          <el-table-column label="规格型号" align="left" prop="invoiceCode" width="140" show-overflow-tooltip/>
                          <el-table-column label="单位" align="left" prop="unit"  show-overflow-tooltip/>
                          <el-table-column label="数量" align="left" prop="qty"  show-overflow-tooltip/>
                          <el-table-column label="单价(不含税)" align="left" prop="withoutPrice" width="120" v-if="isWithout!='含税'" show-overflow-tooltip/>
                          <el-table-column label="金额(不含税)" align="left" prop="withoutAmount" width="120" v-if="isWithout!='含税'"  show-overflow-tooltip/>
                          <el-table-column label="单价(含税)" align="left" prop="price" width="120" v-if="isWithout=='含税'"  show-overflow-tooltip/>
                          <el-table-column label="金额(含税)" align="left" prop="amount" width="120" v-if="isWithout=='含税'"  show-overflow-tooltip/>
                          <el-table-column label="税率" align="left" prop="taxRate"  show-overflow-tooltip/>
                          <el-table-column label="税额" align="left" prop="tax"  show-overflow-tooltip/>
                          <div slot="empty">
                            <svg-icon icon-class="search-none" style="font-size: 64px;" />
                            <p>暂无数据</p>
                          </div>
                        </el-table>
                      </el-descriptions-item>

                    </el-descriptions>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </el-col>
            <el-col :span="14">
              <div style="height: 575px; background-color:#404040;">
                <div v-viewer style="visibility: hidden;height:575px">
                  <img v-for="src in images" :key="src" :src="src" :data-source="src">
                </div>

              </div>
            </el-col>
          </el-row>
        </div>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
    import { listCheckininvoice, getCheckininvoice, delCheckininvoice, addCheckininvoice, updateCheckininvoice } from "@/api/doc/checkininvoice";
    import { listCompany as listcompany, getCompany as getcompany } from "@/api/core/company";
    /* 城市列表 **/
    import { provinceList, cityList, districtList } from "@/api/system/city";
    import { getToken } from "@/utils/auth";

    export default {
        name: "Threematch",
        dicts: ['invoice_status', 'invoice_type', 'sign_status'],
        data() {
            return {
                advanced: false,
                visible: false,
                tableHeight: this.getInitTableHeight(),
                // 遮罩层
                loading: true,
                invoiceEntryList:[],
                // 远程查询条件加载
                remoteSearchValueLoading: false,
                // 关键字查询条件
                searchValueOptions:[

                ],
                // 选中数组
                ids: [],
                // 子表选中数据
                checkedTInCheckinInvoiceEntry: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                tableKey: 15,
                //
                columnsKey: 'threematch',
                // 自定义列
                columns: [
                    // {
          //     key: 0,
          //     label: `公司`,
          //     visible: true
          // },
                    {
                        key: 1,
                        label: `发票类型`,
                        visible: true
                    },
                    {
                        key: 2,
                        label: `发票号码`,
                        visible: true
                    },
                    {
                        key: 3,
                        label: `发票代码`,
                        visible: true
                    },
                    {
                        key: 4,
                        label: `匹配状态`,
                        visible: true
                    },
                    {
                        key: 5,
                        label: `发票状态`,
                        visible: true
                    },
                    {
                        key: 6,
                        label: `开票日期`,
                        visible: true
                    },
                    {
                        key: 7,
                        label: `销方名称`,
                        visible: true
                    },
                    {
                        key: 8,
                        label: `金额(不含税)`,
                        visible: true
                    },
                    {
                        key: 9,
                        label: `税额`,
                        visible: true
                    },
                    {
                        key: 10,
                        label: `金额(含税)`,
                        visible: true
                    },
                    {
                        key: 11,
                        label: `发票备注`,
                        visible: true
                    },
                    {
                        key: 12,
                        label: `ERP发票流水号`,
                        visible: true
                    }
                ],
                // 总条数
                total: 0,
                // 匹配增值税发票表格数据
                checkininvoiceList: [],
                // 匹配增值税发票明细项表格数据
                tInCheckinInvoiceEntryList: [],
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 修改时间时间范围
                daterangeInvoiceDate: [],
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    params:{

                    },
                    invoiceId: null,
                    custId: null,
                    siteCode: null,
                    invoiceType: null,
                    invoiceTypes: [],
                    invoiceNo: null,
                    invoiceCode: null,
                    invoiceDate: null,
                    sellerName: null,
                    sellerNumber: null,
                    sellerTel: null,
                    sellerAccount: null,
                    buyerName: null,
                    buyerNumber: null,
                    buyerTel: null,
                    buyerAccount: null,
                    voucherNumber: null,
                    invoiceStatus: null,
                    invoiceStatuses: [],
                    checkStatus: null,
                    signStatus: null,
                    signStatuses: [],
                    checkCode: null,
                    erpSerialNumber: null,
                    createName: null,
                },
                checkAllInvoiceType: false,
                isInvoiceTypeIndeterminate: false,
                checkAllInvoiceStatus: false,
                isInvoiceStatusIndeterminate: false,
                checkAllSignStatus: false,
                isSignStatusIndeterminate: false,
                // 表单参数
                form: {},
                // 表单校验
                rules: {
                },

                // 导入参数
                upload: {
                    // 是否显示弹出层（导入）
                    open: false,
                    // 弹出层标题（导入）
                    title: "",
                    // 是否禁用上传
                    isUploading: false,
                    // 是否更新已经存在的数据
                    updateSupport: 0,
                    // 设置上传的请求头部
                    headers: { Authorization: "Bearer " + getToken() },
                    // 上传的地址
                    url: null
                },

                detailForm:{

                },
                invoiceOpen:false,
                images:[''],
                isWithout:'含税',

                /* ======================================省市区======================================  */
                // 省
                provinceId: null,
                provinceList:[],
                // 市
                cityId: null,
                cityList:[],
                // 区
                districtId: null,
                districtList:[],

                /* ======================================查询条件-公司代码选择======================================  */
                searchsiteCodes:[],
                searchsiteCodenames:[],
                searchsiteCodeTotal: 0,
                searchsiteCodeList: [],
                searchsiteCodeDialogOpen: false,
                searchsiteCodeSelectLoading: false,
                searchsiteCodeQueryParams: {
                    searchValue: null,
                    pageNum: 1,
                    pageSize: 20,
                },
                /* ======================================编辑-公司代码选择======================================  */
                siteCodename: null,
                siteCodeTotal: 0,
                siteCodeList: [],
                siteCodeDialogRadio: null,
                siteCodeDialogOpen: false,
                siteCodeSelectLoading: false,
                siteCodeQueryParams: {
                    searchValue: null,
                    pageNum: 1,
                    pageSize: 20,
                },
            };
        },
        created() {
            this.getList();
        },
        methods: {
            /** 行样式 */
            rowClass({ row, rowIndex }) {
                if (this.ids.includes(row.id)) {
                    return { background: "#d9edf7", height:'20px' };
                } else {
                    return { height:'20px'};
                }
            },
            /** 隐藏搜索按钮操作 */
            showSearchFun(isShowSearch){
                this.showSearch = isShowSearch
                let oldHeight = this.$refs.queryRef.$el.offsetHeight
                if(!isShowSearch){
                    //当前是显示状态
                    oldHeight = oldHeight + 12
                }else{
                    oldHeight = oldHeight - 12
                }
                this.$nextTick(() => (
                    this.tableHeight = this.$refs.tableRef.$el.offsetHeight - (this.$refs.queryRef.$el.offsetHeight-oldHeight)
                ))
            },
            /** 展开按钮操作 */
            toggleAdvanced() {
                const oldHeight = this.$refs.queryRef.$el.offsetHeight
                this.advanced = !this.advanced
                this.$nextTick(() => (
                    this.tableHeight = this.$refs.tableRef.$el.offsetHeight - (this.$refs.queryRef.$el.offsetHeight-oldHeight)
                ))
            },
            /** 查询匹配增值税发票列表 */
            getList() {
                this.loading = true;
                this.queryParams.params = {};
                if (null != this.daterangeInvoiceDate && '' != this.daterangeInvoiceDate) {
                    this.queryParams.params["beginInvoiceDate"] = this.daterangeInvoiceDate[0];
                    this.queryParams.params["endInvoiceDate"] = this.daterangeInvoiceDate[1];
                }
                listCheckininvoice(this.queryParams).then(response => {
                    this.checkininvoiceList = response.rows;
                    this.total = response.total;
                    this.loading = false;
                });
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                    id: null,
                    invoiceId: null,
                    custId: null,
                    siteCode: null,
                    siteName: null,
                    invoiceType: null,
                    invoiceTypeName: null,
                    invoiceNo: null,
                    invoiceCode: null,
                    invoiceDate: null,
                    printNumber: null,
                    feeWithoutTax: null,
                    fee: null,
                    tax: null,
                    sellerName: null,
                    sellerNumber: null,
                    sellerDest: null,
                    sellerAddress: null,
                    sellerTel: null,
                    sellerBank: null,
                    sellerAccount: null,
                    buyerName: null,
                    buyerNumber: null,
                    buyerAddress: null,
                    buyerTel: null,
                    buyerBank: null,
                    buyerAccount: null,
                    voucherNumber: null,
                    invoiceStatus: null,
                    invoiceStatusName: null,
                    checkStatus: null,
                    checkStatusName: null,
                    signStatus: null,
                    signStatusName: null,
                    checkCode: null,
                    invoiceRemark: null,
                    erpSerialNumber: null,
                    createName: null,
                    createTime: null,
                    updateBy: null,
                    updateTime: null
                };
                this.tInCheckinInvoiceEntryList = [];
                this.resetForm("form");
            },


            /* ※※ 查询 省市区 相关方法 start ※※ */
            // 获取省
            getProvinceList(){
                provinceList().then(response => {
                    this.provinceList = response.data;
                });
            },
            // 获取市
            getCityList(){
                console.log(this.provinceId);
                cityList( {"parentId" : this.provinceId } ).then(response => {
                    this.cityList = response.data;
                });
            },
            // 获取区县
            getDistrictList(){
                districtList( {"parentId" : this.cityId } ).then(response => {
                    this.districtList = response.data;
                });
            },
            // 选中省份
            handleChangeProvince(val){
                // 给表单省字段赋值
                this.form.provinceid = val;
                let province = {};
                province = this.provinceList.find((item)=>{
                    return item.id === val;
                });
                this.form.province = province.name;
                // 城市数据清空、区县数据清空;
                this.cityList = [];
                this.districtList = [];
                // 已选市、区数据清空
                this.cityId = null;
                this.districtId = null;
                // 表单城市、区县数据清空
                this.form.cityid = null;
                this.form.city = null;
                this.form.areaid = null;
                this.form.area = null;
                // 获取城市数据
                this.getCityList();
            },
            // 清空省份
            handleClearProvince(){
                // 城市数据清空、区县数据清空;
                this.cityList = [];
                this.districtList = [];
                // 已选市、区数据清空
                this.cityId = null;
                this.districtId = null;
                // 表单城市、区县数据清空
                this.form.cityid = null;
                this.form.city = null;
                this.form.areaid = null;
                this.form.area = null;
            },
            // 选中城市
            handleChangeCity(val){
                // 给表单市字段赋值
                this.form.cityid = val;
                let city = {};
                city = this.cityList.find((item)=>{
                    return item.id === val;
                });
                this.form.city = city.name;
                // 区县数据清空
                this.districtList = [];
                // 已选区县清空
                this.districtId = null;
                // 表单区县清空
                this.form.areaid = null;
                this.form.area = null;
                // 获取城市数据
                this.getDistrictList();
            },
            // 清空省份
            handleClearCity(){
                // 区县数据清空
                this.districtList = [];
                // 已选区县清空
                this.districtId = null;
                // 表单区县清空
                this.form.areaid = null;
                this.form.area = null;
            },
            // 选中区县
            handleChangeDistrict(val){
                // 给表单省字段赋值
                this.form.areaid = val;
                let district = {};
                district = this.districtList.find((item)=>{
                    return item.id === val;
                });
                this.form.area = district.name;
            },
            // 清空省份
            handleClearDistrict(){
                // 表单区县清空
                this.form.areaid = null;
                this.form.area = null;
            },

            /* ※※ 查询 省市区 相关方法 end ※※ */




            /* ※※ 查询 公司代码 相关方法 start ※※ */
            /** ① 弹出查询条件-公司代码 */
            openSearchsiteCodeDialogOpen(){
                this.searchsiteCodeDialogOpen = true;
                // 默认不查询
            },
            /** ② 单击行 **/
            handleSearchsiteCodeRowClick(row, column, event){
                this.$refs.searchsiteCodeSingleTable.toggleRowSelection(row);
            },
            /** ③ 行KEY **/
            getSearchsiteCodeListRowKey(row) {
                return row.companycode
            },
            /** ④ 选中公司代码 **/
            handleSearchsiteCodeSelectionChange(selection) {
                this.searchsiteCodes = selection.map(item => item.siteCode);
                this.searchsiteCodenames = selection.map(item => item.siteName);
            },
            /** ⑤ 点击查询按钮 **/
            handleSearchsiteCodeQuery(){
                this.searchsiteCodeQueryParams.pageNum = 1;
                this.getSearchsiteCodeList();
            },
            /** ⑥ 查询 **/
            getSearchsiteCodeList(){
                this.searchsiteCodeSelectLoading = true;
                listcompany(this.searchsiteCodeQueryParams).then(response => {
                    this.searchsiteCodeList = response.rows;
                    this.searchsiteCodeTotal = response.total;
                    this.searchsiteCodeSelectLoading = false;
                });
            },
            /** ⑦ 点击确认查询 **/
            confirmSearchsiteCode() {
                if(this.searchsiteCodes.length > 0){
                    this.queryParams.params.siteCodes = this.searchsiteCodes.join(',');
                    this.queryParams.params.companynames = this.searchsiteCodenames.join(',');
                }
                // 关闭查询弹出框
                this.searchsiteCodeCancel();
            },
            /** ⑧ 点击关闭查询弹出框 **/
            searchsiteCodeCancel() {
                this.searchsiteCodeDialogOpen = false;
            },
            /* ※※ 查询 公司代码 相关方法 end ※※ */


            /* ※※ 编辑 公司代码 相关方法 start ※※ */
            /** ① 弹出编辑内容-公司代码 */
            opensiteCodeDialogOpen(){
                this.siteCodeDialogOpen = true;
                this.getsiteCodeList();
            },
            /** ② 单击行 **/
            handlesiteCodeRowClick(row, column, event){
                this.$refs.siteCodeSingleTable.toggleRowSelection(row);
            },
            /** ③ 行KEY **/
            getsiteCodeListRowKey(row) {
                return row.companycode
            },
            /** ④ 选中公司代码 **/
            handlesiteCodeSelectionChange(selection) {
                if (selection[0]) {
                    this.siteCodeDialogRadio = selection[0]
                    this.form.companycode = selection[0].companycode;
                    this.form.companyname = selection[0].companyname;
                }
            },
            /** ⑤ 点击查询按钮 **/
            handlesiteCodeQuery(){
                this.siteCodeQueryParams.pageNum = 1;
                this.getsiteCodeList();
            },
            /** ⑥ 查询 **/
            getsiteCodeList(){
                this.siteCodeSelectLoading = true;
                listcompany(this.siteCodeQueryParams).then(response => {
                    this.siteCodeList = response.rows;
                    this.siteCodeTotal = response.total;
                    this.siteCodeSelectLoading = false;
                });
            },
            /** ⑦ 点击确认查询 **/
            confirmsiteCode() {
                this.siteCodeCancel();
            },
            /** ⑧ 点击关闭查询弹出框 **/
            siteCodeCancel() {
                this.siteCodeDialogOpen = false;
            },
            /* ※※ 编辑 公司代码 相关方法 end ※※ */


            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.daterangeInvoiceDate = [];
                this.resetForm("queryForm");
                this.handleQuery();
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.id)
                this.single = selection.length!==1
                this.multiple = !selection.length
            },
            /** 导入按钮操作 */
            handleImport() {
                this.upload.title = "批量导入匹配";
                this.upload.open = true;
                this.upload.url = this.getBaseURL() + "/post/order/importOrderPackageEntry";
            },

            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.open = true;
                this.title = "添加匹配增值税发票";
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                const id = row.id || this.ids
                getCheckininvoice(id).then(response => {
                    this.form = response.data;
                    this.tInCheckinInvoiceEntryList = response.data.tInCheckinInvoiceEntryList;
                    this.open = true;
                    this.title = "修改匹配增值税发票";
                });
            },
            /** 提交按钮 */
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        this.form.tInCheckinInvoiceEntryList = this.tInCheckinInvoiceEntryList;
                        if (this.form.id != null) {
                            updateCheckininvoice(this.form).then(response => {
                                this.$modal.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            });
                        } else {
                            addCheckininvoice(this.form).then(response => {
                                this.$modal.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            });
                        }
                    }
                });
            },
            /** 跳转至详情页 */
            jumpToDetail(row){
                const invoiceId = row.invoiceId;
                const invoiceNo = row.invoiceNo;
                // 需要另新增一个标签页
                this.$router.push({path:'/doc/checkin/in/detail/' + invoiceId,query:{invoiceId:invoiceId, invoiceNo:invoiceNo, date:new Date().getTime()}})
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                const ids = row.id || this.ids;
                this.$modal.confirm('是否确认删除匹配增值税发票编号为"' + ids + '"的数据项？').then(function() {
                    return delCheckininvoice(ids);
                }).then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                }).catch(() => {});
            },
            /** 匹配增值税发票明细项序号 */
            rowTInCheckinInvoiceEntryIndex({ row, rowIndex }) {
                row.index = rowIndex + 1;
            },
            /** 匹配增值税发票明细项添加按钮操作 */
            handleAddTInCheckinInvoiceEntry() {
                let obj = {};
                obj.entryId = "";
                obj.custId = "";
                obj.siteCode = "";
                obj.siteName = "";
                obj.productCode = "";
                obj.productName = "";
                obj.specificatCode = "";
                obj.unit = "";
                obj.qty = "";
                obj.withoutPrice = "";
                obj.withoutAmount = "";
                obj.taxRate = "";
                obj.tax = "";
                obj.price = "";
                obj.amount = "";
                obj.createName = "";
                this.tInCheckinInvoiceEntryList.push(obj);
            },
            /** 匹配增值税发票明细项删除按钮操作 */
            handleDeleteTInCheckinInvoiceEntry() {
                if (this.checkedTInCheckinInvoiceEntry.length == 0) {
                    this.$modal.msgError("请先选择要删除的匹配增值税发票明细项数据");
                } else {
                    const tInCheckinInvoiceEntryList = this.tInCheckinInvoiceEntryList;
                    const checkedTInCheckinInvoiceEntry = this.checkedTInCheckinInvoiceEntry;
                    this.tInCheckinInvoiceEntryList = tInCheckinInvoiceEntryList.filter(function(item) {
                        return checkedTInCheckinInvoiceEntry.indexOf(item.index) == -1
                    });
                }
            },
            /** 复选框选中数据 */
            handleTInCheckinInvoiceEntrySelectionChange(selection) {
                this.checkedTInCheckinInvoiceEntry = selection.map(item => item.index)
            },
            /** 导出按钮操作 */
            handleExport() {
                this.download('doc/checkininvoice/export', {
                    ...this.queryParams
                }, `checkininvoice_${new Date().getTime()}.xlsx`)
            },

            /** 动态加载关键字查询条件 */
            remoteSearchValue(query) {
                this.remoteSearchValueLoading = true;
                if (query !== '') {
                    this.searchValueOptions = [
                        {value: '销方名称:' + query ,label: '销方名称:' + query },
                        {value: '发票号:' + query ,label: '发票号:' + query },
                        {value: '发票代码:' + query ,label: '发票代码:' + query },
                    ];
                    this.searchValueOptions.map(item => {
                        this.queryParams.searchValues.map((item2, index) => {
                            if(item.value.startsWith('销方名称') && item2.startsWith('销方名称')){
                                item.disabled = true;
                            }
                            if(item.value.startsWith('发票号') && item2.startsWith('发票号')){
                                item.disabled = true;
                            }
                            if(item.value.startsWith('发票代码') && item2.startsWith('发票代码')){
                                item.disabled = true;
                            }
                        })
                    });
                } else {
                    this.searchValueOptions = [];
                }
                this.remoteSearchValueLoading = false;
            },

            checkAll(val, column){
                if(val){
                    switch (column) {
                        case 'invoiceType':
                            this.dict.type.invoice_type.map((dict, index) => {
                                this.queryParams.invoiceTypes.push(dict.value)
                            });
                            break;
                        case 'invoiceStatus':
                            this.dict.type.invoice_status.map((dict, index) => {
                                this.queryParams.invoiceStatuses.push(dict.value)
                            });
                            break;
                        case 'signStatus':
                            this.dict.type.sign_status.map((dict, index) => {
                                this.queryParams.signStatuses.push(dict.value)
                            });
                            break;
                    }

                } else {
                    switch (column) {
                        case 'invoiceType':
                            this.queryParams.invoiceTypes = []
                            break;
                        case 'invoiceStatus':
                            this.queryParams.invoiceStatuses = []
                            break;
                        case 'signStatus':
                            this.queryParams.signStatuses = []
                            break;
                    }
                }
                switch (column) {
                    case 'invoiceType':
                        this.isInvoiceTypeIndeterminate = false;
                        break;
                    case 'invoiceStatus':
                        this.isInvoiceStatusIndeterminate = false;
                        break;
                    case 'signStatus':
                        this.isSignStatusIndeterminate = false;
                        break;
                }
            },

            handleCheckedChange(value, column){
                let checkedCount = value.length;
                switch (column) {
                    case 'invoiceType':
                        this.checkAllInvoiceType = checkedCount === this.dict.type.invoice_type.length;
                        this.isInvoiceTypeIndeterminate = checkedCount > 0 && checkedCount < this.dict.type.invoice_type.length;
                        break;
                    case 'invoiceStatus':
                        this.checkAllInvoiceStatus = checkedCount === this.dict.type.invoice_status.length;
                        this.isInvoiceStatusIndeterminate = checkedCount > 0 && checkedCount < this.dict.type.invoice_status.length;
                        break;
                    case 'signStatus':
                        this.checkAllSignStatus = checkedCount === this.dict.type.sign_status.length;
                        this.isSignStatusIndeterminate = checkedCount > 0 && checkedCount < this.dict.type.sign_status.length;
                        break;
                }
            },

            /** 下载模板操作 */
            importTemplate() {
                this.download('doc/checkininvoice/importTemplate', {}, `三单匹配导入模板_${new Date().getTime()}.xlsx`)
            },

            // 提交上传文件
            submitFileForm() {
                this.$refs.upload.submit();
            },

            // 文件上传中处理
            handleFileUploadProgress(event, file, fileList) {
                this.upload.isUploading = true;
            },

            // 文件上传成功处理
            handleFileSuccess(response, file, fileList) {
                this.upload.open = false;
                this.upload.isUploading = false;
                this.$refs.upload.clearFiles();
                this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
                //
            },

            handleOpenInvoice() {
                this.invoiceOpen = true;
                // TODO 获取附件

            },
        }
    };
</script>
